<template>
  <div class="main">
    <a-form
      id="formLogin"
      class="user-layout-login"
      ref="formLogin"
      :form="form"
      @submit="handleSubmit"
    >
      <a-tabs
        :activeKey="customActiveKey"
        :tabBarStyle="{ textAlign: 'center', borderBottom: 'unset' }"
        @change="handleTabClick"
      >
        <!-- <a-tab-pane key="tab1" tab="账号密码登录">
                    <div style="padding-top: 4px;"></div>
                    <a-alert v-if="isLoginError && customActiveKey === 'tab1'" type="error" showIcon style="margin-bottom: 24px;" message="账户或密码错误" />
                    <a-form-item>
                        <a-input size="large" type="text" placeholder="请输入帐户名" v-decorator="['username',{rules: [{ required: true, message: '请输入帐户名' }], validateTrigger: 'change'}]">
                            <a-icon slot="prefix" type="user" :style="{ color: 'rgba(0,0,0,.25)' }" />
                        </a-input>
                    </a-form-item>
                    <div style="padding-top: 4px;"></div>
                    <a-form-item>
                        <a-input size="large" type="password" autocomplete="false" placeholder="请输入密码" v-decorator="['password',{rules: [{ required: true, message: '请输入密码' }], validateTrigger: 'blur'}]">
                            <a-icon slot="prefix" type="lock" :style="{ color: 'rgba(0,0,0,.25)' }" />
                        </a-input>
                    </a-form-item>
                    <div style="padding-top: 14px;"></div>
                </a-tab-pane> -->
        <a-tab-pane key="tab2" tab="手机号登录">
          <div style="padding-top: 4px"></div>
          <a-alert
            v-if="isLoginError && customActiveKey === 'tab2'"
            type="error"
            showIcon
            style="margin-bottom: 24px"
            message="手机号或验证码错误"
          />
          <a-form-item>
            <a-input
              size="large"
              type="text"
              placeholder="手机号"
              v-decorator="[
                'mobile',
                {
                  rules: [
                    {
                      required: true,
                      pattern: /^1[23456789]\d{9}$/,
                      message: '请输入正确的手机号',
                    },
                  ],
                  validateTrigger: 'change',
                },
              ]"
            >
              <a-icon
                slot="prefix"
                type="mobile"
                :style="{ color: 'rgba(0,0,0,.25)' }"
              />
            </a-input>
          </a-form-item>
          <div style="padding-top: 4px"></div>
          <a-row :gutter="16">
            <a-col class="gutter-row" :span="16">
              <a-form-item>
                <a-input
                  size="large"
                  type="text"
                  placeholder="验证码"
                  v-decorator="[
                    'captcha',
                    {
                      rules: [{ required: true, message: '请输入验证码' }],
                      validateTrigger: 'blur',
                    },
                  ]"
                >
                  <a-icon
                    slot="prefix"
                    type="mail"
                    :style="{ color: 'rgba(0,0,0,.25)' }"
                  />
                </a-input>
              </a-form-item>
            </a-col>
            <a-col class="gutter-row" :span="8">
              <a-button
                class="getCaptcha"
                tabindex="-1"
                :disabled="state.smsSendBtn"
                @click.stop.prevent="getCaptcha"
                v-text="
                  (!state.smsSendBtn && '获取验证码') || state.time + ' s'
                "
              ></a-button>
            </a-col>
          </a-row>
          <div style="padding-top: 14px"></div>
        </a-tab-pane>
      </a-tabs>
      <a-form-item>
        <a-button
          size="large"
          type="primary"
          htmlType="submit"
          class="login-button"
          :loading="state.loginBtn"
          :disabled="state.loginBtn"
          >确定
        </a-button>
      </a-form-item>
    </a-form>
  </div>
</template>
<script>
import Vue from "vue";
import env from "@/config/env";
// import TwoStepCaptcha from '@/components/tools/TwoStepCaptcha';
import { userLogin, GetSendsms, LoginByMobile } from "@/api/passport";
import { ACCESS_TOKEN, USER_RULE } from "@/store/mutation-types";
import { showErrors, showError, showSuccess } from "@/utils/showMsg";
import { mapActions } from "vuex";
export default {
  components: {
    // TwoStepCaptcha,
  },
  data() {
    return {
      customActiveKey: "tab2",
      loginBtn: false,
      // login type: 0 email, 1 username, 2 telephone
      loginType: 0,
      isLoginError: false,
      requiredTwoStepCaptcha: false,
      stepCaptchaVisible: false,
      form: this.$form.createForm(this),
      state: {
        time: 60,
        loginBtn: false,
        // login type: 0 email, 1 username, 2 telephone
        loginType: 0,
        smsSendBtn: false,
      },
      wrapperCol: { span: 24 },
    };
  },
  methods: {
    ...mapActions({
      storeLogin: "user/Login",
      // InfoData: 'user/UserInfo',
    }),
    // 切换账号登陆还是手机号码登陆
    handleTabClick(key) {
      this.customActiveKey = key;
      this.form.resetFields();
    },
    // 登陆 //账号登陆,手机验证码登陆
    handleSubmit(e) {
      const that = this;
      e.preventDefault();
      const {
        form: { validateFields },
        state,
        customActiveKey,
        Login,
      } = this;
      state.loginBtn = true;
      const validateFieldsKey =
        customActiveKey === "tab1"
          ? ["username", "password"]
          : ["mobile", "captcha"];
      validateFields(validateFieldsKey, { force: true }, (err, values) => {
        if (!err) {
          const loginParams = {
            // username: values.username,
            //   password: values.password,
          };
          if (customActiveKey === "tab1") {
            loginParams["username"] = values.username;
            loginParams["password"] = values.password;
            userLogin(loginParams)
              .then((res) => {
                // console.log(res);
                if (res.data.code == 1) {
                  // console.log(res);
                  this.isLoginError = false;
                  this.storeLogin({
                    accessToken: res.data.data.user.token.access_token,
                    UserData: {
                      name: res.data.data.nickname,
                      headimg: res.data.data.headimg
                        ? res.data.data.headimg
                        : require("../../assets/images/avatar.png"),
                      UserId: res.data.data.user.id,
                      // MarketId: res.data.data.user.m_id,
                      // MarketName: res.data.data.user.market_name,
                      pid: res.data.data.user.pid,
                      identityId: res.data.data.user.identity_id,
                      identityType: res.data.data.user.identity_type,
                    },
                  });

                  showSuccess(res.data.msg);
                  this.$router.push({ path: "/" });
                  // 延迟 1 秒显示欢迎信息
                  setTimeout(() => {
                    this.$notification.success({
                      message: "欢迎",
                      description: `${res.data.data.nickname}，欢迎回来`,
                    });
                  }, 1000);
                  // userMessage()
                  //     .then(info => {
                  //         if (info.data.code == 1) {
                  //             // console.log(res.data);
                  //             let data = info.data.data
                  //             let infodata = {
                  //                 RouterList: data.data,
                  //                 RouteArr: data.route
                  //             }
                  //             Vue.ls.set(USER_RULE, infodata, env.tokenExpires);
                  //             showSuccess(res.data.msg);
                  //             this.$router.push({ path: '/' });
                  //             // 延迟 1 秒显示欢迎信息
                  //             setTimeout(() => {
                  //                 this.$notification.success({
                  //                     message: '欢迎',
                  //                     description: `${res.data.data.nickname}，欢迎回来`
                  //                 })
                  //             }, 1000)
                  //         } else {
                  //             showError(info.data.msg);
                  //         }
                  //     });
                  // this.InfoData()
                } else {
                  showError(res.data.msg);
                  this.isLoginError = true;
                }
                state.loginBtn = false;
              })
              .catch((err) => {
                showError(err);
                this.isLoginError = false;
              });
          } else {
            loginParams["mobile"] = values.mobile;
            loginParams["code"] = values.captcha;
            LoginByMobile(loginParams)
              .then((res) => {
                console.log(res);
                if (res.data.code == 1) {
                  if (
                    res.data.data.partner_type == "supplier" ||
                    res.data.data.partner_type == "medical" ||
                    res.data.data.partner_type == "yxn_supplier"
                  ) {
                    that.isLoginError = false;
                    that.storeLogin({
                      accessToken: res.data.data.token.access_token,
                      UserData: {
                        name: res.data.data.store_name,
                        headimg: res.data.data.store_logo
                          ? res.data.data.store_logo
                          : require("../../assets/images/avatar.png"),
                        UserId: res.data.data.user_id,
                        // MarketId: res.data.data.user.m_id,
                        // MarketName: res.data.data.user.market_name,
                        pid: res.data.data.p_identity_id,
                        identityId: res.data.data.identity_id,
                        identityType: res.data.data.identity_type,
                      },
                    });

                    // 权限（暂写死）
                    let RouterList = []; //菜单列表
                    let RouteArr = []; //路由列表
                    if (res.data.data.partner_type == "supplier") {
                      RouterList = [
                        {
                          name: "商品管理",
                          route: "/ShopGoods",
                          children: [
                            {
                              name: "商品列表",
                              route: "/ShopGoods/ShopGoodsIndex",
                            },
                            {
                              name: "商品信息",
                              route: "/ShopGoods/goodsDetails",
                            },
                            {
                              name: "商品编辑",
                              route: "/ShopGoods/goodsDetailsEdit",
                            },
                          ],
                        },
                        {
                          name: "订单管理",
                          route: "/OrderManage",
                          children: [
                            {
                              name: "订单列表",
                              route: "/OrderManage/orderList",
                            },
                            {
                              name: "订单详情",
                              route: "/OrderManage/orderDetails",
                            },
                            {
                              name: "售后/退货",
                              route: "/OrderManage/afterSale",
                            },
                          ],
                        },
                        {
                          name: "绑定管理",
                          route: "/BindSupplier",
                          children: [
                            {
                              name: "绑定药店列表",
                              route: "/BindSupplier/BindMedicalList",
                            },
                            {
                              name: "绑定销售经理列表",
                              route: "/BindSupplier/BindSalesList",
                            },
                            {
                              name: "绑定销售代表列表",
                              route: "/BindSupplier/BindSalesClient",
                            },
                          ],
                        },
                        {
                          name: "店铺轮播图",
                          route: "/supplierBanner",
                          children: [
                            {
                              name: "轮播图信息",
                              route: "/supplierBanner/supplierBannerDetail",
                            },
                          ],
                        },
                      ];
                      RouteArr = [
                        "/ShopGoods",
                        "/ShopGoodsIndex",
                        "/goodsDetails",
                        "/goodsDetailsEdit",
                        "/OrderManage",
                        "/orderList",
                        "/orderDetails",
                        "/afterSale",
                        "/BindSupplier",
                        "/BindMedicalList",
                        "/BindSalesList",
                        "/BindSalesClient",
                        "/supplierBanner",
                        "/supplierBannerDetail"
                      ];
                    } else if (res.data.data.partner_type == "medical") {
                      RouterList = [
                        {
                          name: "DIY模板",
                          route: "/DiyTemplate",
                          children: [
                            {
                              name: "装修模板",
                              route: "/DiyTemplate/DiyTemplateIndex",
                            },
                            {
                              name: "店铺装修",
                              route: "/DiyTemplate/DiyDecorationIndex",
                            },
                          ],
                        },
                      ];
                      RouteArr = [
                        "/DiyTemplate",
                        "/DiyTemplateIndex",
                        "/DiyDecorationIndex",
                      ];
                    } else if(res.data.data.partner_type == "yxn_supplier"){
                        RouterList = [
                        {
                          name: "商品管理",
                          route: "/ShopSupplierSG",
                          children: [
                            {
                              name: "商品列表",
                              route: "/ShopSupplierSGIndex",
                            },
                            {
                              name: "商品信息",
                              route: "/ShopSupplierGoodsDetails",
                            },
                            {
                              name: "商品信息",
                              route: "/ShopSupplierProductDetails",
                            },
                          ],
                        },
                      ];
                      RouteArr = [
                        "/ShopSupplierSG",
                        "/ShopSupplierSGIndex",
                        "/ShopSupplierGoodsDetails",
                        "/ShopSupplierProductDetails",
                      ];
                    }

                    let infodata = {
                      RouterList,
                      RouteArr,
                    };
                    console.log(infodata);
                    Vue.ls.set(USER_RULE, infodata, env.tokenExpires);

                    showSuccess(res.data.msg);
                    that.$router.push({ path: "/" });
                    // 延迟 1 秒显示欢迎信息
                    setTimeout(() => {
                      that.$notification.success({
                        message: "欢迎",
                        description: `${res.data.data.store_name}，欢迎回来`,
                      });
                    }, 1000);
                  } else {
                    state.loginBtn = false;
                    showError("登录账号不是药店或供应商身份！");
                    return;
                  }
                } else {
                  showError(res.data.msg);
                  this.isLoginError = true;
                }
                state.loginBtn = false;
              })
              .catch((err) => {
                showError(err);
                this.isLoginError = false;
              });
          }
        } else {
          setTimeout(() => {
            state.loginBtn = false;
          }, 600);
        }
      });
    },
    // 获取验证码
    getCaptcha(e) {
      e.preventDefault();
      const {
        form: { validateFields },
        state,
      } = this;
      validateFields(["mobile"], { force: true }, (err, values) => {
        if (!err) {
          state.smsSendBtn = true;
          const interval = window.setInterval(() => {
            if (state.time-- <= 0) {
              state.time = 60;
              state.smsSendBtn = false;
              window.clearInterval(interval);
            }
          }, 1000);
          const hide = this.$message.loading("验证码发送中..", 0);
          GetSendsms({ mobile: values.mobile })
            .then((res) => {
              setTimeout(hide, 2500);
              this.$notification.success({
                message: "提示",
                description: `验证码获取成功`,
                duration: 8,
              });
            })
            .catch((err) => {
              setTimeout(hide, 1);
              clearInterval(interval);
              state.time = 60;
              state.smsSendBtn = false;
              this.requestFailed(err);
            });
        }
      });
    },
  },
};
</script>
<style lang="less" scoped>
.user-layout-login {
  label {
    font-size: 14px;
  }

  .getCaptcha {
    display: block;
    width: 100%;
    height: 40px;
  }

  .forge-password {
    font-size: 14px;
  }

  button.login-button {
    padding: 0 15px;
    font-size: 16px;
    height: 40px;
    width: 100%;
  }

  .user-login-other {
    text-align: left;
    margin-top: 24px;
    line-height: 22px;

    .item-icon {
      font-size: 24px;
      color: rgba(0, 0, 0, 0.2);
      margin-left: 16px;
      vertical-align: middle;
      cursor: pointer;
      transition: color 0.3s;

      &:hover {
        color: #1890ff;
      }
    }

    .register {
      float: right;
    }
  }
}
</style>